<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="价格" prop="productPrice">
        <el-input
          v-model="queryParams.productPrice"
          placeholder="请输入商品价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数量" prop="productQuantity">
        <el-input
          v-model="queryParams.productQuantity"
          placeholder="请输入购买数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="总价" prop="productTotalPrice">
        <el-input
          v-model="queryParams.productTotalPrice"
          placeholder="请输入商品总价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- 只保留导出功能，删除新增和删除按钮 -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fun:item:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="itemList">
      <el-table-column label="用户" align="center" prop="userName" width="120" />
      <el-table-column label="订单号" align="center" prop="orderNo" show-overflow-tooltip />
      <el-table-column label="商品名称" align="center" prop="productName" width="150" show-overflow-tooltip />
      <el-table-column label="商品图片" align="center" prop="productImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.productImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品品牌" align="center" prop="productBrand" width="120" show-overflow-tooltip />
      <el-table-column label="商品分类" align="center" prop="productCategory" width="120" show-overflow-tooltip />
      <el-table-column label="商品规格" align="center" prop="productSpec" width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.productSpec">
            <el-tag
              v-for="(value, key) in parseProductSpec(scope.row.productSpec)"
              :key="key"
              type="primary"
              plain
              size="mini"
              style="margin: 2px;"
            >
              {{ key }}: {{ value }}
            </el-tag>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="商品价格" align="center" prop="productPrice" />
      <el-table-column label="购买数量" align="center" prop="productQuantity" />
      <el-table-column label="商品总价" align="center" prop="productTotalPrice" />

    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单ID" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单ID" />
        </el-form-item>
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="商品ID" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入商品ID" />
        </el-form-item>
        <el-form-item label="SKU ID" prop="skuId">
          <el-input v-model="form.skuId" placeholder="请输入SKU ID" />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品图片" prop="productImage">
          <image-upload v-model="form.productImage"/>
        </el-form-item>
        <el-form-item label="商品品牌" prop="productBrand">
          <el-input v-model="form.productBrand" placeholder="请输入商品品牌" />
        </el-form-item>
        <el-form-item label="商品分类" prop="productCategory">
          <el-input v-model="form.productCategory" placeholder="请输入商品分类" />
        </el-form-item>
        <el-form-item label="商品规格" prop="productSpec">
          <el-input v-model="form.productSpec" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商品价格" prop="productPrice">
          <el-input v-model="form.productPrice" placeholder="请输入商品价格" />
        </el-form-item>
        <el-form-item label="购买数量" prop="productQuantity">
          <el-input v-model="form.productQuantity" placeholder="请输入购买数量" />
        </el-form-item>
        <el-form-item label="商品总价" prop="productTotalPrice">
          <el-input v-model="form.productTotalPrice" placeholder="请输入商品总价" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listItem, getItem, delItem, addItem, updateItem } from "@/api/fun/item"

export default {
  name: "Item",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单商品表格数据
      itemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        orderNo: null,
        productId: null,
        skuId: null,
        productName: null,
        productImage: null,
        productBrand: null,
        productCategory: null,
        productSpec: null,
        productPrice: null,
        productQuantity: null,
        productTotalPrice: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderId: [
          { required: true, message: "订单ID不能为空", trigger: "blur" }
        ],
        orderNo: [
          { required: true, message: "订单号不能为空", trigger: "blur" }
        ],
        productId: [
          { required: true, message: "商品ID不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        productPrice: [
          { required: true, message: "商品价格不能为空", trigger: "blur" }
        ],
        productQuantity: [
          { required: true, message: "购买数量不能为空", trigger: "blur" }
        ],
        productTotalPrice: [
          { required: true, message: "商品总价不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    // 检查是否有订单号参数，如果有则自动过滤
    if (this.$route.query.orderNo) {
      this.queryParams.orderNo = this.$route.query.orderNo
    }
    this.getList()
  },
  methods: {
    /** 查询订单商品列表 */
    getList() {
      this.loading = true
      listItem(this.queryParams).then(response => {
        console.log('=== 订单商品列表API返回数据 ===', response)
        console.log('=== 商品列表数据 ===', response.rows)
        if (response.rows && response.rows.length > 0) {
          console.log('=== 第一条商品数据 ===', response.rows[0])
          console.log('=== 第一条商品的productImage字段 ===', response.rows[0].productImage)
        }
        this.itemList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        orderItemId: null,
        orderId: null,
        orderNo: null,
        productId: null,
        skuId: null,
        productName: null,
        productImage: null,
        productBrand: null,
        productCategory: null,
        productSpec: null,
        productPrice: null,
        productQuantity: null,
        productTotalPrice: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderItemId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加订单商品"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const orderItemId = row.orderItemId || this.ids
      getItem(orderItemId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改订单商品"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderItemId != null) {
            updateItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addItem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderItemIds = row.orderItemId || this.ids
      this.$modal.confirm('是否确认删除订单商品编号为"' + orderItemIds + '"的数据项？').then(function() {
        return delItem(orderItemIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fun/item/export', {
        ...this.queryParams
      }, `item_${new Date().getTime()}.xlsx`)
    },
    /** 解析商品规格JSON */
    parseProductSpec(productSpec) {
      try {
        if (typeof productSpec === 'string') {
          // 尝试解析JSON格式
          return JSON.parse(productSpec)
        }
        return productSpec || {}
      } catch (e) {
        // 如果不是有效的JSON格式，返回一个包含原始值的对象
        console.warn('解析商品规格失败，返回原始值:', productSpec)
        return { spec: productSpec } || {}
      }
    }
  }
}
</script>
